﻿namespace Hidistro.UI.Web.Admin.product
{
    using ASPNET.WebControls;
    using Hidistro.ControlPanel.Commodities;
    using Hidistro.ControlPanel.Store;
    using Hidistro.Core;
    using Hidistro.Core.Entities;
    using Hidistro.Core.Enums;
    using Hidistro.Entities.Commodities;
    using Hidistro.Entities.Store;
    using Hidistro.UI.ControlPanel.utility;
    using Ionic.Zip;
    using Ionic.Zlib;
    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Data;
    using System.Globalization;
    using System.IO;
    using System.Text;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    [PrivilegeCheck(Privilege.ProductBatchExport)]
    public class ExportToLocal : AdminPage
    {
        private readonly string _applicationPath;
        private readonly DirectoryInfo _baseDir = new DirectoryInfo(HttpContext.Current.Request.MapPath("~/storage/data/local"));
        private int? _categoryId;
        private readonly Encoding _encoding = Encoding.Unicode;
        private DateTime? _endDate;
        private readonly string _flag = DateTime.Now.ToString("yyyyMMddHHmmss");
        private bool _includeInStock;
        private bool _includeOnSales;
        private bool _includeUnSales;
        private string _productCode;
        private string _productName;
        private DateTime? _startDate;
        private readonly string _url;
        private DirectoryInfo _workDir;
        private readonly string _zipFilename;
        protected Button btnExport;
        protected Button btnSearch;
        protected WebCalendar calendarEndDate;
        protected WebCalendar calendarStartDate;
        protected CheckBox chkExportImages;
        protected CheckBox chkInStock;
        protected CheckBox chkOnSales;
        protected CheckBox chkUnSales;
        protected ProductCategoriesDropDownList dropCategories;
        protected Grid grdProducts;
        protected Label lblTotals;
        protected Pager pager;
        protected TextBox txtSearchText;
        protected TextBox txtSKU;

        public ExportToLocal()
        {
            this._zipFilename = string.Format("local{0}.zip", this._flag);
        }

        private void BindProducts()
        {
            if ((!this._includeUnSales && !this._includeOnSales) && !this._includeInStock)
            {
                this.ShowMsg("至少要选择包含一个商品状态", false);
            }
            else
            {
                DbQueryResult exportProducts = ProductHelper.GetExportProducts(this.GetQuery(), (string) this.ViewState["RemoveProductIds"]);
                this.grdProducts.DataSource = exportProducts.Data;
                this.grdProducts.DataBind();
                this.pager.TotalRecords = exportProducts.TotalRecords;
                this.lblTotals.Text = exportProducts.TotalRecords.ToString(CultureInfo.InvariantCulture);
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            string text1 = "http://" + HttpContext.Current.Request.Url.Host + ((HttpContext.Current.Request.Url.Port == 80) ? "" : (":" + HttpContext.Current.Request.Url.Port)) + Globals.ApplicationPath;
            string applicationPath = Globals.ApplicationPath;
            DataTable table = ProductHelper.GetExportProducts(this.GetQuery(), true, true, (string) this.ViewState["RemoveProductIds"]).Tables[3];
            List<ProductDetail> list = new List<ProductDetail>();
            foreach (DataRow row in table.Rows)
            {
                Dictionary<int, IList<int>> dictionary;
                int productId = Convert.ToInt32(row["ProductId"]);
                IList<int> tagsId = null;
                ProductInfo info = ProductHelper.GetProductDetails(productId, out dictionary, out tagsId);
                ProductDetail item = new ProductDetail {
                    pi = info,
                    attrs = dictionary,
                    tagIds = tagsId
                };
                list.Add(item);
            }
            this._workDir = this._baseDir.CreateSubdirectory(this._flag);
            string csvFilename = this._workDir.FullName + string.Format(@"\local{0}.csv", this._flag);
            string path = csvFilename.Replace(".csv", "");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            this.DoExportForHishop(csvFilename, path, list);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            this.ReSearchProducts();
        }

        public string ConvertNull(object obj)
        {
            if ((obj is DBNull) || (obj == null))
            {
                obj = "";
            }
            return obj.ToString().Replace("\t", " ").Replace("\r\n", "");
        }

        private void DoExportForHishop(string csvFilename, string imagePath, List<ProductDetail> list)
        {
            string path = csvFilename;
            using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                string productCSVForHishop = this.GetProductCSVForHishop(imagePath, list);
                UnicodeEncoding encoding = new UnicodeEncoding();
                int byteCount = encoding.GetByteCount(productCSVForHishop);
                byte[] preamble = encoding.GetPreamble();
                byte[] dst = new byte[preamble.Length + byteCount];
                System.Buffer.BlockCopy(preamble, 0, dst, 0, preamble.Length);
                encoding.GetBytes(productCSVForHishop.ToCharArray(), 0, productCSVForHishop.Length, dst, preamble.Length);
                stream.Write(dst, 0, dst.Length);
            }
            using (ZipFile file = new ZipFile())
            {
                DirectoryInfo info = new DirectoryInfo(imagePath);
                file.CompressionLevel = CompressionLevel.Default;
                file.AddFile(path, "");
                file.AddDirectory(info.FullName, info.Name);
                HttpResponse response = HttpContext.Current.Response;
                response.ContentType = "application/x-zip-compressed";
                response.ContentEncoding = this._encoding;
                response.AddHeader("Content-Disposition", "attachment; filename=" + info.Name + ".zip");
                response.Clear();
                file.Save(response.OutputStream);
                this._workDir.Delete(true);
                response.Flush();
                response.Close();
            }
        }

        private string GetProductCSVForHishop(string imagePath, List<ProductDetail> list)
        {
            StringBuilder builder = new StringBuilder();
            string format = "\r\n-1\t\"{0}\"\t\"{1}\"\t\"{2}\"\t\"{3}\"\t\"{4}\"\t\"{5}\"\t\"{6}\"\t\"{7}\"\t\"{8}\"\t\"{9}\"\t\"{10}\"\t\"{11}\"\t\"{12}\"\t\"{13}\"\t\"{14}\"\t\"{15}\"\t\"{16}\"\t\"{17}\"\t{18}\t\"{19}\"\t\"{20}\"\t\"{21}\"\t\"{22}\"\t\"{23}\"\t\"{24}\"\t\"{25}\"\t\"{26}\"";
            builder.Append("\"id\"\t\"所属分类\"\t\"商品类型\"\t\"商品名称\"\t\"商家编码\"\t\"简单描述\"\t\"计量单位\"\t");
            builder.Append("\"详细描述\"\t\"详细页标题\"\t\"详细页描述\"\t\"详细页搜索关键字\"\t\"销售状态\"\t");
            builder.Append("\"图片\"\t\"图片2\"\t\"图片3\"\t\"图片4\"\t\"图片5\"\t");
            builder.Append("\"市场价\"\t\"品牌\"\t\"是否有规格\"\t");
            builder.Append("\"规格属性\"\t\"货号\"\t\"重量\"\t\"库存\"\t成本价\"\t\"一口价\"\t");
            builder.Append("\"商品属性\"\t\"商品标签\"");
            foreach (ProductDetail detail in list)
            {
                string str2;
                string str3;
                string str4;
                string str5;
                string str6;
                string str = "{" + Guid.NewGuid().ToString() + "}.htm";
                using (StreamWriter writer = new StreamWriter(Path.Combine(imagePath, str), false, Encoding.GetEncoding("gb2312")))
                {
                    if (!string.IsNullOrEmpty(detail.pi.Description))
                    {
                        string description = detail.pi.Description;
                        writer.Write(description);
                    }
                }
                if (!string.IsNullOrEmpty(detail.pi.ImageUrl1) && !detail.pi.ImageUrl1.StartsWith("http://"))
                {
                    str2 = detail.pi.ImageUrl1;
                    if (File.Exists(base.Server.MapPath("~" + str2)))
                    {
                        FileInfo info = new FileInfo(base.Server.MapPath("~" + str2));
                        str2 = info.Name.ToLower();
                        info.CopyTo(Path.Combine(imagePath, str2), true);
                    }
                }
                else
                {
                    str2 = "";
                }
                if (!string.IsNullOrEmpty(detail.pi.ImageUrl2) && !detail.pi.ImageUrl2.StartsWith("http://"))
                {
                    str3 = detail.pi.ImageUrl2;
                    if (File.Exists(base.Server.MapPath("~" + str3)))
                    {
                        FileInfo info2 = new FileInfo(base.Server.MapPath("~" + str3));
                        str3 = info2.Name.ToLower();
                        info2.CopyTo(Path.Combine(imagePath, str3), true);
                    }
                }
                else
                {
                    str3 = "";
                }
                if (!string.IsNullOrEmpty(detail.pi.ImageUrl3) && !detail.pi.ImageUrl3.StartsWith("http://"))
                {
                    str4 = detail.pi.ImageUrl3;
                    if (File.Exists(base.Server.MapPath("~" + str4)))
                    {
                        FileInfo info3 = new FileInfo(base.Server.MapPath("~" + str4));
                        str4 = info3.Name.ToLower();
                        info3.CopyTo(Path.Combine(imagePath, str4), true);
                    }
                }
                else
                {
                    str4 = "";
                }
                if (!string.IsNullOrEmpty(detail.pi.ImageUrl4) && !detail.pi.ImageUrl4.StartsWith("http://"))
                {
                    str5 = detail.pi.ImageUrl4;
                    if (File.Exists(base.Server.MapPath("~" + str5)))
                    {
                        FileInfo info4 = new FileInfo(base.Server.MapPath("~" + str5));
                        str5 = info4.Name.ToLower();
                        info4.CopyTo(Path.Combine(imagePath, str5), true);
                    }
                }
                else
                {
                    str5 = "";
                }
                if (!string.IsNullOrEmpty(detail.pi.ImageUrl5) && !detail.pi.ImageUrl5.StartsWith("http://"))
                {
                    str6 = detail.pi.ImageUrl5;
                    if (File.Exists(base.Server.MapPath("~" + str6)))
                    {
                        FileInfo info5 = new FileInfo(base.Server.MapPath("~" + str6));
                        str6 = info5.Name.ToLower();
                        info5.CopyTo(Path.Combine(imagePath, str6), true);
                    }
                }
                else
                {
                    str6 = "";
                }
                string str10 = "";
                string str11 = "";
                string str12 = "";
                string str13 = "";
                string str14 = "";
                string str15 = "";
                string str16 = "";
                string str17 = "";
                string str18 = "";
                string skuId = detail.pi.SkuId;
                foreach (SKUItem item in detail.pi.Skus.Values)
                {
                    str11 = str11 + item.SKU + ";";
                    str12 = str12 + ((this.ConvertNull(item.Weight) == "") ? "0" : this.ConvertNull(item.Weight)) + ";";
                    str13 = str13 + item.Stock + ";";
                    str14 = str14 + ((this.ConvertNull(item.CostPrice) == "") ? "0" : this.ConvertNull(item.CostPrice)) + ";";
                    str15 = str15 + item.SalePrice + ";";
                }
                if (str14 == "")
                {
                    str14 = "0";
                }
                if (str13 == "")
                {
                    str13 = "0";
                }
                if (!this.chkExportImages.Checked)
                {
                    str2 = str3 = str4 = str5 = str6 = "";
                }
                if (detail.pi.TypeId.HasValue)
                {
                    int local1 = detail.pi.TypeId.Value;
                    foreach (KeyValuePair<int, IList<int>> pair in detail.attrs)
                    {
                        string attributeName = ProductTypeHelper.GetAttribute(pair.Key).AttributeName;
                        foreach (int num in pair.Value)
                        {
                            string valueStr = ProductTypeHelper.GetAttributeValueInfo(num).ValueStr;
                            string str26 = str16;
                            str16 = str26 + attributeName + ":" + valueStr + ",";
                        }
                    }
                    DataTable tags = CatalogHelper.GetTags();
                    foreach (int num2 in detail.tagIds)
                    {
                        foreach (DataRow row in tags.Rows)
                        {
                            if (row["TagId"].Equals(num2))
                            {
                                str17 = str17 + row["TagName"] + ",";
                                break;
                            }
                        }
                    }
                }
                switch (detail.pi.SaleStatus)
                {
                    case ProductSaleStatus.OnSale:
                        str18 = "出售中";
                        break;

                    case ProductSaleStatus.UnSale:
                        str18 = "下架区";
                        break;

                    case ProductSaleStatus.OnStock:
                        str18 = "仓库中";
                        break;
                }
                bool hasSKU = detail.pi.HasSKU;
                if (hasSKU)
                {
                    foreach (SKUItem item2 in detail.pi.Skus.Values)
                    {
                        foreach (KeyValuePair<int, int> pair2 in item2.SkuItems)
                        {
                            string str21 = ProductTypeHelper.GetAttribute(pair2.Key).AttributeName;
                            foreach (AttributeValueInfo info6 in ProductTypeHelper.GetAttribute(pair2.Key).AttributeValues)
                            {
                                if (info6.ValueId.Equals(pair2.Value))
                                {
                                    string str22 = info6.ValueStr;
                                    str10 = str10 + str21 + ":" + str22;
                                    break;
                                }
                            }
                            str10 = str10 + ",";
                        }
                        str10 = str10.Trim(new char[] { ',' }) + ";";
                    }
                }
                string name = "";
                CategoryInfo category = CatalogHelper.GetCategory(detail.pi.CategoryId);
                if (category != null)
                {
                    name = category.Name;
                }
                string typeName = "";
                if (detail.pi.TypeId.HasValue)
                {
                    typeName = ProductTypeHelper.GetProductType(detail.pi.TypeId.Value).TypeName;
                }
                string brandName = "";
                if (detail.pi.BrandId.HasValue)
                {
                    brandName = CatalogHelper.GetBrandCategory(detail.pi.BrandId.Value).BrandName;
                }
                builder.AppendFormat(format, new object[] { 
                    this.ConvertNull(name), this.ConvertNull(typeName), detail.pi.ProductName, this.ConvertNull(detail.pi.ProductCode), this.ConvertNull(detail.pi.ShortDescription), this.ConvertNull(detail.pi.Unit), str, this.ConvertNull(detail.pi.Title), this.ConvertNull(detail.pi.MetaDescription), this.ConvertNull(detail.pi.MetaKeywords), str18, str2, str3, str4, str5, str6, 
                    this.ConvertNull(detail.pi.MarketPrice), this.ConvertNull(brandName), hasSKU ? "1" : "0", str10.Trim(new char[] { ';' }), str11.Trim(new char[] { ';' }), str12.Trim(new char[] { ';' }), str13.Trim(new char[] { ';' }), str14.Trim(new char[] { ';' }), str15.Trim(new char[] { ';' }), str16.Trim(new char[] { ',' }), str17.Trim(new char[] { ',' })
                 });
            }
            return builder.ToString();
        }

        private AdvancedProductQuery GetQuery()
        {
            AdvancedProductQuery entity = new AdvancedProductQuery {
                Keywords = this._productName,
                ProductCode = this._productCode,
                CategoryId = this._categoryId,
                PageSize = this.pager.PageSize,
                PageIndex = this.pager.PageIndex,
                SaleStatus = ProductSaleStatus.OnSale,
                SortOrder = SortAction.Desc,
                SortBy = "DisplaySequence",
                StartDate = this._startDate,
                EndDate = this._endDate,
                IncludeInStock = this._includeInStock,
                IncludeOnSales = this._includeOnSales,
                IncludeUnSales = this._includeUnSales
            };
            if (this._categoryId.HasValue)
            {
                entity.MaiCategoryPath = CatalogHelper.GetCategory(this._categoryId.Value).Path;
            }
            Globals.EntityCoding(entity, true);
            return entity;
        }

        private void grdProducts_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Remove")
            {
                int rowIndex = ((GridViewRow) ((Control) e.CommandSource).NamingContainer).RowIndex;
                int num2 = (int) this.grdProducts.DataKeys[rowIndex].Value;
                string str = (string) this.ViewState["RemoveProductIds"];
                if (string.IsNullOrEmpty(str))
                {
                    str = num2.ToString();
                }
                else
                {
                    str = str + "," + num2.ToString();
                }
                this.ViewState["RemoveProductIds"] = str;
                this.BindProducts();
            }
        }

        private void LoadParameters()
        {
            int num;
            DateTime time;
            DateTime time2;
            this._productName = this.txtSearchText.Text.Trim();
            if (!string.IsNullOrEmpty(this.Page.Request.QueryString["productName"]))
            {
                this._productName = Globals.UrlDecode(this.Page.Request.QueryString["productName"]);
                this.txtSearchText.Text = this._productName;
            }
            this._productCode = this.txtSKU.Text.Trim();
            if (!string.IsNullOrEmpty(this.Page.Request.QueryString["productCode"]))
            {
                this._productCode = Globals.UrlDecode(this.Page.Request.QueryString["productCode"]);
                this.txtSKU.Text = this._productCode;
            }
            this._categoryId = this.dropCategories.SelectedValue;
            if (!string.IsNullOrEmpty(this.Page.Request.QueryString["categoryId"]) && int.TryParse(this.Page.Request.QueryString["categoryId"], out num))
            {
                this._categoryId = new int?(num);
                this.dropCategories.SelectedValue = this._categoryId;
            }
            this._startDate = this.calendarStartDate.SelectedDate;
            if (!string.IsNullOrEmpty(this.Page.Request.QueryString["startDate"]) && DateTime.TryParse(this.Page.Request.QueryString["startDate"], out time))
            {
                this._startDate = new DateTime?(time);
                this.calendarStartDate.SelectedDate = this._startDate;
            }
            this._endDate = this.calendarEndDate.SelectedDate;
            if (!string.IsNullOrEmpty(this.Page.Request.QueryString["endDate"]) && DateTime.TryParse(this.Page.Request.QueryString["endDate"], out time2))
            {
                this._endDate = new DateTime?(time2);
                this.calendarEndDate.SelectedDate = this._endDate;
            }
            this._includeOnSales = this.chkOnSales.Checked;
            if (!string.IsNullOrEmpty(this.Page.Request.QueryString["includeOnSales"]))
            {
                bool.TryParse(this.Page.Request.QueryString["includeOnSales"], out this._includeOnSales);
                this.chkOnSales.Checked = this._includeOnSales;
            }
            this._includeUnSales = this.chkUnSales.Checked;
            if (!string.IsNullOrEmpty(this.Page.Request.QueryString["includeUnSales"]))
            {
                bool.TryParse(this.Page.Request.QueryString["includeUnSales"], out this._includeUnSales);
                this.chkUnSales.Checked = this._includeUnSales;
            }
            this._includeInStock = this.chkInStock.Checked;
            if (!string.IsNullOrEmpty(this.Page.Request.QueryString["includeInStock"]))
            {
                bool.TryParse(this.Page.Request.QueryString["includeInStock"], out this._includeInStock);
                this.chkInStock.Checked = this._includeInStock;
            }
        }

        protected override void OnInitComplete(EventArgs e)
        {
            base.OnInitComplete(e);
            this.btnSearch.Click += new EventHandler(this.btnSearch_Click);
            this.btnExport.Click += new EventHandler(this.btnExport_Click);
            this.grdProducts.RowCommand += new GridViewCommandEventHandler(this.grdProducts_RowCommand);
            if (!this.Page.IsPostBack)
            {
                this.dropCategories.DataBind();
            }
            this.LoadParameters();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.Page.IsPostBack)
            {
                this.BindProducts();
            }
        }

        private void ReSearchProducts()
        {
            NameValueCollection values2 = new NameValueCollection();
            values2.Add("productName", Globals.UrlEncode(this.txtSearchText.Text.Trim()));
            values2.Add("productCode", Globals.UrlEncode(Globals.HtmlEncode(this.txtSKU.Text.Trim())));
            values2.Add("pageSize", this.pager.PageSize.ToString());
            values2.Add("includeOnSales", this.chkOnSales.Checked.ToString());
            values2.Add("includeUnSales", this.chkUnSales.Checked.ToString());
            values2.Add("includeInStock", this.chkInStock.Checked.ToString());
            NameValueCollection queryStrings = values2;
            if (this.dropCategories.SelectedValue.HasValue)
            {
                queryStrings.Add("categoryId", this.dropCategories.SelectedValue.ToString());
            }
            queryStrings.Add("pageIndex", this.pager.PageIndex.ToString());
            if (this.calendarStartDate.SelectedDate.HasValue)
            {
                queryStrings.Add("startDate", this.calendarStartDate.SelectedDate.Value.ToString());
            }
            if (this.calendarEndDate.SelectedDate.HasValue)
            {
                queryStrings.Add("endDate", this.calendarEndDate.SelectedDate.Value.ToString());
            }
            base.ReloadPage(queryStrings);
        }

        private class ProductDetail
        {
            public Dictionary<int, IList<int>> attrs;
            public ProductInfo pi;
            public IList<int> tagIds;
        }
    }
}

